package radubrehar;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import radubrehar.util.HibernateUtil;

/**
 * Servlet implementation class for Servlet: HitCounterReceiver
 * 
 */
public class HitCounterReceiver extends javax.servlet.http.HttpServlet
		implements javax.servlet.Servlet {
	
	static final long serialVersionUID = 1L;
	
	private final static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public HitCounterReceiver() {
		super();
	}
	
	/*
	@Override
	public void init(){
		sessionFactory = HibernateUtil.getSessionFactory();
	}
	*/

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// TODO Auto-generated method stub
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String url = request.getParameter("link");
		
		PrintWriter out = response.getWriter();
		
		out.println("we received " + url);

		out.close();
		
		Session session = this.sessionFactory.openSession();
		Transaction tr = session.beginTransaction();
		Link link = LinkManager.getLinkWithURL(url);
		
		link.incrementHits();
		
		LinkManager.saveOrUpdate(link);
		
		tr.commit();
		
	}}